package com.yunwaikeji.gy_tool_library.utils;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;

import androidx.annotation.RequiresApi;
import androidx.core.content.FileProvider;

import java.io.File;

public class GYApkUtils {
    public static Intent getInstallIntent(Context context, String authority, File apkFile) {
        if (apkFile == null) {
            return null;
        }
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
            //7.0以下
            return installIntentOld(apkFile);
        } else {
            //7.0及以上
            return installIntent7(context, authority, apkFile);
        }
    }

    public static void startInstall(Context context, String authority, File apkFile) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            boolean hasInstallPermission = isHasInstallPermissionWithO(context);
            if (!hasInstallPermission) {
                startInstallPermissionSettingActivity(context);
                return;
            }
        }
        context.startActivity(getInstallIntent(context, authority, apkFile));
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    private static boolean isHasInstallPermissionWithO(Context context) {
        if (context == null) {
            return false;
        }
        return context.getPackageManager().canRequestPackageInstalls();
    }

    /**
     * 开启设置安装未知来源应用权限界面
     *
     * @param context
     */
    @RequiresApi(api = Build.VERSION_CODES.O)
    private static void startInstallPermissionSettingActivity(Context context) {
        if (context == null) {
            return;
        }
        Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES);
        ((Activity) context).startActivityForResult(intent, 0);
    }

    /**
     * 7.0以下
     *
     * @param file
     */
    private static Intent installIntentOld(File file) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
        return intent;
    }

    /**
     * 7.0及以上
     */
    private static Intent installIntent7(Context context, String authority, File file) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        //参数1 上下文, 参数2 Provider主机地址 和配置文件中保持一致   参数3  共享的文件
        Uri apkUri = FileProvider.getUriForFile(GYUtils.scanForActivity(context), authority, file);
        //添加这一句表示对目标应用临时授权该Uri所代表的文件
        intent.setAction(Intent.ACTION_INSTALL_PACKAGE);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        intent.addCategory("android.intent.category.DEFAULT");
        intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
        return intent;
    }
}
